package com.example.util;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

public class HttpUtils {

	private static final OkHttpClient client = createOkHttpClient();

	private static OkHttpClient createOkHttpClient() {
		OkHttpClient okHttpClient = new OkHttpClient();
		okHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
		okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
		okHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
		return okHttpClient;
	}

	public static String doGet(String url) throws IOException {
		Request request = new Request.Builder()
				.url(url)
				.get()
				.build();
		Response response = client.newCall(request).execute();
		if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
		return response.body().string();
	}

	public static String doPostForm(String url, Map<String, String> parameters) throws IOException {
		FormEncodingBuilder formBodyBuilder = new FormEncodingBuilder();
		for (Map.Entry<String, String> entry : parameters.entrySet()) {
			formBodyBuilder.add(entry.getKey(), entry.getValue());
		}
		Request request = new Request.Builder()
				.url(url)
				.post(formBodyBuilder.build())
				.build();
		Response response = client.newCall(request).execute();
		if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
		return response.body().string();
	}

	private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
	public static String doPostJson(String url, String json) throws IOException {
		Request request = new Request.Builder()
				.url(url)
				.post(RequestBody.create(MEDIA_TYPE_JSON, json))
				.build();
		Response response = client.newCall(request).execute();
		if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
		return response.body().string();
	}

}
